<template>
	<!-- 城市选择-->
	<view class="city-select">
		<!-- 预留搜索-->
		<view class="search-msg-box flex-a-center" v-if="isSearch" :style="'padding-top:'+statusBarHeight+'px'">
			<back :borderColor="'#333'" :padding="'4rpx 0 0'" @click="goBack"></back>
			<view class="search-msg flex-center-between">
				<search :width="'441rpx'" :height="'68rpx'" :margin="'10rpx 0 10rpx 24rpx'" :backgroundColor="'#F7F7F7'" @input="keyInput"></search>
			</view>
		</view>
		<scroll-view :scroll-top="scrollTop" scroll-y="true" class="city-select-main" id="city-select-main" :scroll-into-view="toView" @scroll="onLeftScroll" :style="{paddingTop:statusBarHeight+44+'px'}">
			<!-- 当前定位城市 -->
			<view class="where flex-center-between" v-if="activeCity && !serachCity">
				<view class="flex">
					您所在城市：<view @click="cityTrigger(activeCity)">{{ activeCity[formatName] }}{{districtName||app.globalData.districtName||''}}</view>
				</view>
				<view class="right flex-a-center" @click="countyDis=!countyDis">
					<text>选择县区</text>
					<back v-if="!countyDis" :isBottom="true" :borderColor="'#333'" :padding="'4rpx 0 0'"></back>
					<back v-else :isTop="true" :borderColor="'#333'" :padding="'4rpx 0 0'"></back>
				</view>
			</view>
			<!-- 县区 -->
			<view class="hot-city animated fadeIn fast" v-if="countyDistrict.length > 0 && countyDis && !serachCity">
				<view class="flex-wrap">
					<view class="hot-city-item" v-for="(item, index) in countyDistrict" :key="index"  @click="districtTrigger(item, 'countyDistrict')">
						{{ item[formatName] }}
					</view>
				</view>
			</view>
			<!-- 热门城市 -->
			<view class="hot-city" v-if="hotCity.length > 0 && !serachCity">
				<view class="title">
					热门城市
				</view>
				<view class="flex-wrap">
					<view class="hot-city-item" v-for="(item, index) in hotCity" :key="index"  @click="cityTrigger(item, 'hot')">
						{{ item[formatName] }}
					</view>
				</view>
			</view>
			<!-- 城市列表(搜索前) -->
			<view class="citys" v-if="!serachCity">
				<view v-for="(city, index) in sortItems" :key="index" class="city-list-top">
					<view v-if="city.isCity" class="citys-row">
						<view class="citys-item-letter" :id="'city-letter-' + (city.name === '#' ? '0' : city.name)">{{ city.name }}</view>
						<view class="citys-item" v-for="(item, inx) in city.citys" :key="inx" @click="cityTrigger(item)">{{ item.cityName }}</view>
					</view>
				</view>
			</view>
			<!-- 城市列表(搜索后) -->
			<view class="citys" v-if="serachCity">
				<view v-if="searchDatas.length > 0">
					<view v-for="(item, index) in searchDatas" :key="index" class="citys-row">
						<view class="citys-item" @click="cityTrigger(item.oldData)">
							{{ item.name }}
						</view>
					</view>
				</view>
				<view v-else class="no-results">
					<text>未找到相关城市</text>
				</view>
			</view>
		</scroll-view>
		<!-- 城市选择索引-->
		<view class="city-indexs-view" v-if="!serachCity" :style="{top:statusBarHeight+124+'px'}">
			<view class="city-indexs">
				<view v-for="(cityIns, index) in handleCity" class="city-indexs-text" v-show="cityIns.isCity" :key="index" @click="cityindex(cityIns.forName)" :style="topIndex==index?{fontSize:'26rpx'}:{}">
					{{ cityIns.name }}
				</view>
			</view>
		</view>
	</view>
</template>

<script>

import citySelect from './citySelect.js';
import { systemStore } from '@/stores/system'
export default {
	props: {
		//查询提示文字
		placeholder: {
			type: String,
			default: '请输入城市名称'
		},
		//传入要排序的名称
		formatName: {
			type: String,
			default: 'cityName'
		},
		//当前定位城市
		activeCity: {
			type: Object,
			default: () => null
		},
		//县区
		countyDistrict: {
			type: Array,
			default: () => []
		},
		//热门城市
		hotCity: {
			type: Array,
			default: () => []
		},
		//城市数据
		obtainCitys: {
			type: Array,
			default: () => []
		},
		//是否有搜索
		isSearch: {
			type: Boolean,
			default: true
		},
		// 县区名字
		districtName: {
			type: String
		},
	},
	data() {
		return {
			toView: 'city-letter-Find', //锚链接 初始值
			scrollTop: 0, //scroll-view 滑动的距离
			cityindexs: [], // 城市索引
			activeCityIndex: '', // 当前所在的城市索引
			handleCity: [], // 处理后的城市数据
			serachCity: '', // 搜索的城市
			cityData: [],
			statusBarHeight:null,
			countyDis:false ,//是否展示县区
			cityListTop:[],
			topIndex:null,
			app: getApp()
		};
	},
	computed: {
		/**
		 * @desc 城市列表排序
		 * @return  Array
		 */
		sortItems() {
			for (let index = 0; index < this.handleCity.length; index++) {
				if (this.handleCity[index].isCity) {
					let cityArr = this.handleCity[index].citys;
					cityArr = cityArr.sort(function(a, b) {
						var value1 = a.unicode;
						var value2 = b.unicode;
						return value1 - value2;
					});
				}
			}
			return this.handleCity;
		},
		/**
		 * @desc 搜索后的城市列表
		 * @return Array
		 */
		searchDatas() {
			if (!this.serachCity) return [];
			const searchData = [];
			const searchKey = this.serachCity.trim().toLowerCase();
			console.log('这个')
			for (let i = 0; i < this.cityData.length; i++) {
				const cityName = this.cityData[i][this.formatName].toLowerCase();
				if (cityName.includes(searchKey)) {
					searchData.push({
						oldData: this.cityData[i],
						name: this.cityData[i][this.formatName],
					});
				}
			}
			return searchData;
		}
	},
	created() {
		// 初始化城市数据
		this.cityData = this.obtainCitys;
		this.initializationCity();
		this.buildCityindexs();
    const SystemStore =systemStore()
   this.statusBarHeight =  SystemStore.statusBarInfo.statusBarHeight
		console.log(this.statusBarHeight,'this.statusBarHeight')

	},
	mounted() {
		this.cityListTop = []
		const query = uni.createSelectorQuery().in(this);
		query
		  .selectAll(".city-list-top")
		  .boundingClientRect((data) => {
			 // console.log(data)
			 data.map(v=>{
				if(v.top!=0){
					this.cityListTop.push(v.top)
				}
			})
			console.log(this.cityListTop,'cityListTop')
		  })
		  .exec();
	},
	watch: {
		obtainCitys(newData) {
			this.updateCitys(newData);
		}
	},
	methods: {
		/**
		 * @desc 初始化
		 */
		updateCitys(data) {
			if (data && data.length) {
				this.cityData = data;
				this.initializationCity();
				this.buildCityindexs();
			}
		},
		/**
		 * @desc 监听输入框的值
		 */
		keyInput(e) {
			// 确保 e 是字符串类型，避免调用 trim 时出错
			this.serachCity = e.detail.value
			console.log('e',e)
		},
		/**
		 * @desc 初始化城市数据
		 * @return undefind
		 */
		initializationCity() {
			this.handleCity = [];
			const cityLetterArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '#'];
			for (let index = 0; index < cityLetterArr.length; index++) {
				this.handleCity.push({
					name: cityLetterArr[index],
					isCity: false, // 用于区分是否含有当前字母开头的城市
					citys: [], // 存放城市首字母含是此字母的数组
					forName: 'city-letter-' + (cityLetterArr[index] == '#' ? '0' : cityLetterArr[index]) //label的绑定
				});
			}
		},
		/**
		 * @desc 得到城市的首字母
		 * @param str String
		 */
		getLetter(str) {
			return citySelect.getFirstLetter(str[0]);
		},
		/**
		 * @desc 构建城市索引
		 * @return undefind
		 */
		buildCityindexs() {
			this.cityindexs = [];
			for (let i = 0; i < this.cityData.length; i++) {
				// 获取首字母
				const cityLetter = this.getLetter(this.cityData[i][this.formatName]).firstletter;
				// 获取当前城市首字母的unicode，用作后续排序
				const unicode = this.getLetter(this.cityData[i][this.formatName]).unicode;

				const index = this.cityIndexPosition(cityLetter);
				if (this.cityindexs.indexOf(cityLetter) === -1) {
					this.handleCity[index].isCity = true;
					this.cityindexs.push(cityLetter);
				}

				this.handleCity[index].citys.push({
					cityName: this.cityData[i][this.formatName],
					unicode: unicode,
					oldData: this.cityData[i]
				});
			}
		},
		/**
		 * @desc 滑动到城市索引所在的地方
		 * @param id String 城市索引
		 */
		cityindex(id) {
			this.toView = id;
			// //创建节点查询器
			// const query = uni.createSelectorQuery().in(this)
			// var that = this
			// that.scrollTop = 0
			// //滑动到指定位置(解决方法:重置到顶部，重新计算，影响:页面会闪一下)
			// setTimeout(() => {
			// 	query
			// 		.select('#city-letter-' + (id === '#' ? '0' : id))
			// 		.boundingClientRect(data => {
			// 			// console.log("得到布局位置信息" + JSON.stringify(data));
			// 			// console.log("节点离页面顶部的距离为" + data.top);
			// 			data ? (that.scrollTop = data.top) : void 0
			// 		})
			// 		.exec()
			// }, 0)
		},
		/**
		 * @desc 获取城市首字母的unicode
		 * @param letter String 城市索引
		 */
		cityIndexPosition(letter) {
			if (!letter) {
				return '';
			}
			const ACode = 65;
			return letter === '#' ? 26 : letter.charCodeAt(0) - ACode;
		},
		/** @desc 城市列表点击事件
		 *  @param Object
		 */
		cityTrigger(item) {
			// 传值到父组件
			this.$emit('cityClick', item.oldData ? item.oldData : item);
		},
		/** @desc 县区列表点击事件
		 *  @param Object
		 */
		districtTrigger(item) {
			// 传值到父组件
			this.$emit('districtClick', item.oldData ? item.oldData : item);
		},
		goBack(){
			uni.navigateBack()
		},
		onLeftScroll(e){
			// console.log('e',e.detail.scrollTop)
			for(let i=0;i<this.cityListTop.length;i++){
				// console.log(this.cityListTop[i],'v')
				// console.log(i,'k')
				if(this.cityListTop[i]>(e.detail.scrollTop+85)){
					// console.log(this.topIndex,'this.topIndex---')
					this.topIndex = i-1
					return
				}
			}
	}
	}
};
</script>

<style lang="scss">
.search-msg-box{
	width: 750rpx;
	background-color: #fff;
	padding-left: 24rpx;
	position: fixed;
	left: 0;
	z-index: 9;
	.search-msg{
		width: 65%
	}
}
.where{
	font-weight: normal;
	color: #555;
	margin: 24rpx;
	.right{
		text{
			margin-right: 12rpx;
		}
	}
}

//宽度转换vw
// @function vww($number) {
// 	@return ($number / 375) * 750 + rpx;
// }

view {
	box-sizing: border-box;
}

.city-select-main {
	position: relative;
	// overflow: scroll;
	// -webkit-overflow-scrolling: touch;
	width: 100%;
	height: 100%;
	// overflow-y: auto;
}

.city-select {
	position: relative;
	width: 100vw;
	height: 100vh;
	font-weight: bold;
	// 热门城市
	.hot-city{
		margin: 8rpx 54rpx 0 24rpx;
		.title{
			margin-bottom: 24rpx;
		}
		.hot-city-item{
			margin: 0 24rpx 24rpx 0;
			width: 200rpx;
			height: 66rpx;
			line-height: 66rpx;
			text-align: center;
			border: 1rpx solid #9F9F9F;
			border-radius: 10rpx;
		}
	}

	.citys {
		margin: 0 78rpx 0 24rpx;
		.citys-row {
			// padding-left: vww(18);
			width: 100%;
			.citys-item-letter {
				line-height: 40rpx;
				margin-top: 8rpx;
			}

			.citys-item {
				padding: 24rpx 0;
				border-bottom: 1px solid #ebebf0;

				&:last-child {
					border: none;
				}
			}
		}
	}

	.city-indexs-view {
		position: absolute;
		right: 0;
		z-index: 999;

		.city-indexs {

			font-size: 24rpx;

			.city-indexs-text {
				margin: 4rpx 24rpx;
				width: 23rpx;
				height: 33rpx;
				line-height: 33rpx;
				text-align: center;
				// background-color: red;
				&:last-child {
					margin-bottom: 0;
				}
			}
		}
	}
}

.no-results {
	text-align: center;
	color: #999;
	margin-top: 20rpx;
	font-size: 28rpx;
}
</style>
